package com.mohansever.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mohansever.common.WxHttpReq;
import com.mohansever.common.WxLogin;
import com.mohansever.dao.UserDao;
import com.mohansever.pojo.User;
import com.mohansever.rep.UserPageRep;
import com.mohansever.rep.WxLoginRep;
import com.mohansever.rep.WxUserRep;
import com.mohansever.service.UserService;
import com.mohansever.tool.Base64CC;
import com.mohansever.tool.Token;
import com.mohansever.tool.UserId;
import com.mohansever.util.ErrStatusEnum;
import com.mohansever.util.PageData;
import com.mohansever.util.PageQUery;
import com.mohansever.util.ResponseUtil;
import com.mohansever.util.TokenUserInfo;
import com.mohansever.util.UserMap;
import com.mohansever.util.WxLoginInfo;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	private UserDao userDao;
	
	/**
	 * 用户使用userId和userPwd登录
	 */	
	@Override
	public ResponseUtil mangerLogin(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		ResponseUtil rep = new ResponseUtil();
		try {
			User user = userDao.loginByUserIdAndUserPwd(pd);
			if (user == null) {
				//用户名或密码错误
				rep.fail(ErrStatusEnum.LOGINERR.getCode(), ErrStatusEnum.LOGINERR.getMessage());
			} else {
				//检查用户状态,是否是禁用
				if (user.getUserStatus() == 2) {
					rep.fail(ErrStatusEnum.USERDISABLE.getCode(), ErrStatusEnum.USERDISABLE.getMessage());
				} else {
					//生成token
					String token = Token.create();
					System.out.println("token = " + token);
					if (token == null) {
						rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
					} else {
						TokenUserInfo tui = new TokenUserInfo(pd.getString("userId"),user.getRole(),user.getUserStatus(),token);
						UserMap.UserId2TokenMap.put(pd.getString("userId"), tui);
						Map<String, Object> data = new HashMap<String, Object>();
						data.put("role",user.getRole());
						data.put("userStatus", user.getUserStatus());
						data.put("token", token);
						rep.defaultSuccess(data);
					}
				}		
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 修改用户的状态
	 */
	@Override
	public ResponseUtil editUserStatus(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		
		try {
			if (UserMap.UserId2TokenMap.get(pd.getString("userId")).getRole() < 3 ) {
				User user = this.userDao.selectUserByUserId(pd.getString("userId"));
				if (user == null) {
					rep.fail(ErrStatusEnum.NOTARGET.getCode(), ErrStatusEnum.NOTARGET.getMessage());
				}else {
					if (UserMap.UserId2TokenMap.get(pd.getString("userId")).getRole() < user.getRole()) {
						user.setUserStatus(pd.getInt("userStatus"));
						this.userDao.updateUserStatus(user);
						rep.defaultSuccess("用户状态修改成功");
					} else {
						rep.fail(ErrStatusEnum.POWERERR.getCode(), ErrStatusEnum.POWERERR.getMessage());
					}
				}
			} else {
				rep.fail(ErrStatusEnum.POWERERR.getCode(), ErrStatusEnum.POWERERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 通过userId删除用户
	 */
	@Override
	public ResponseUtil deleteUser(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		
		try {
			if (UserMap.UserId2TokenMap.get(pd.getString("userId")).getRole() == 1) {
				this.userDao.deleteByUserId(pd.getString("targetUserId"));
				rep.defaultSuccess("删除用户成功");
			} else {
				rep.fail(ErrStatusEnum.POWERERR.getCode(), ErrStatusEnum.POWERERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 分页获取用户
	 */
	@Override
	public ResponseUtil getPageList(PageData pd){
		ResponseUtil rep = new ResponseUtil();
		try {
			int rStart = 0;
			int rEnd = 0;
			if (UserMap.UserId2TokenMap.get(pd.getString("userId")).getRole() == 1) {
				if (pd.getInt("role") == 1) {
					rStart = 1;
					rEnd = 4;
				}else {
					rStart = pd.getInt("role");
					rEnd = pd.getInt("role");
				}
				rep = getUserList(rStart,rEnd,pd);
			} else {
				if (pd.getInt("role") == 1) {
					rStart = 2;
					rEnd = 4;
				}else {
					rStart = pd.getInt("role");
					rEnd = pd.getInt("role");
				}
				rep = getUserList(rStart,rEnd,pd);
			}		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 微信登录
	 */
	@Override
	public ResponseUtil wxLogin(PageData pd){
		ResponseUtil rep = new ResponseUtil();
		try {
			/**
			 * 1.根据code获取openId
			 */
			String openidJson = WxHttpReq.httpsGetOpenId(pd.getString("code"));
			if (openidJson == null) {
				rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
			} else {
				/**
				 * 2.解析json
				 */
				WxLogin wxLogin = new WxLogin();
				if (wxLogin.paserOpenId(openidJson)) {
					rep.fail(ErrStatusEnum.WXLOGINERR.getCode(), ErrStatusEnum.WXLOGINERR.getMessage());
				} else {
					PageData pData = this.userDao.selectUserByOpenId(wxLogin.getOpenid());
					if (pData == null) {
						/**
						 * 新用户
						 */
						WxLoginRep wxLRep = new WxLoginRep(wxLogin.getOpenid());
						WxLoginInfo wxLoginInfo = new WxLoginInfo(wxLogin.getOpenid(),wxLogin.getSession_key(),wxLogin.getUnionid());
						UserMap.WxLoginMap.put(wxLogin.getOpenid(), wxLoginInfo);
						rep.defaultSuccess(wxLRep);
					} else {
						/**
						 * 老用户
						 */
						if (pData.getInt("userStatus") == 2) {
							rep.fail(ErrStatusEnum.USERDISABLE.getCode(), ErrStatusEnum.USERDISABLE.getMessage());
						} else {
							WxLoginRep wxLRep = wxOldLogin(pData,wxLogin);
							if (wxLRep == null) {
								rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
							}else {
								rep.defaultSuccess(wxLRep);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 添加微信用户信息
	 */
	@Override
	public ResponseUtil wxAddUserInfo(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			/**
			 * 1.检测openId是否已经存在
			 */
			if (UserMap.WxLoginMap.containsKey(pd.getString("openId"))) {
				/**
				 * 2.生成userId并检测是否可用
				 */
				String userId = null;
				for (int i = 0; i < 5; i++) {
					String uId = UserId.createUserId();
					Integer isOk = this.userDao.selectUserIdIsExist(uId);
					if (isOk == null) {
						userId = uId;
					}				
				}
				if (userId == null) {
					rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
				}else{
					/**
					 * 3.插入数据库
					 */
					pd.put("userId", userId);
					pd.put("userName", Base64CC.decode(pd.getString("nickName")));
					pd.remove("nickName");				
					pd.put("nickName", pd.getString("userName"));
					pd.put("role", 4);
					pd.put("userStatus", 1);
					this.userDao.insertWxUser(pd);
					
					/**
					 * 3.生成token
					 */
					String token = Token.create();
					System.out.println("token = " + token);
					TokenUserInfo tui = new TokenUserInfo(pd.getString("userId"),pd.getInt("role"),pd.getInt("userStatus"),token);
					UserMap.UserId2TokenMap.put(pd.getString("userId"), tui);
					Map<String, String> wxInfoRep = new HashMap<String,String>();
					wxInfoRep.put("userId", userId);
					wxInfoRep.put("token", token);
					rep.defaultSuccess(wxInfoRep);				
				}
			} else {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	private ResponseUtil getUserList(int rStart,int rEnd,PageData pd){
		ResponseUtil rep = new ResponseUtil();
		PageQUery pq = new PageQUery();
	
		pq.setStart(rStart);
		pq.setEnd(rEnd);
		
		Integer recordSize = this.userDao.selectRecordSizeByRole(pq);
		if (recordSize == null) {
			//数据为0
			UserPageRep uPageRep = new UserPageRep();
			uPageRep.setTotalRecord(0);
			rep.defaultSuccess(uPageRep);
		} else {
			int totalRecord = recordSize.intValue();
			//int pageSize = (int) Math.ceil(totalRecord/(pData.getInt("eachPageSize") * 1.0));
			int start = (pd.getInt("queryPage") - 1)*pd.getInt("eachPageSize");
			pq.setBegin(start);
			pq.setEach(pd.getInt("eachPageSize"));						
			List<PageData> users = this.userDao.selectPageList(pq);
			UserPageRep uPageRep = new UserPageRep();
			uPageRep.setTotalRecord(totalRecord);
			uPageRep.setUsers(users);
			rep.defaultSuccess(uPageRep);
		}
	
		return rep;
	}
	
	public WxLoginRep wxOldLogin(PageData pd,WxLogin wxLogin) throws UnsupportedEncodingException{
		WxLoginRep wxLRep = new WxLoginRep();
		/**
		 * 1.生成token
		 */
		String token = Token.create();
		System.out.println("token = " + token);
		if (token == null) {
			wxLRep = null;
		} else {
			//存储微信返回的session_key和unionid
			WxLoginInfo wxLoginInfo = new WxLoginInfo(wxLogin.getOpenid(),wxLogin.getSession_key(),wxLogin.getUnionid());
			UserMap.WxLoginMap.put(wxLogin.getOpenid(), wxLoginInfo);
			
			TokenUserInfo tui = new TokenUserInfo(pd.getString("userId"),pd.getInt("role"),pd.getInt("userStatus"),token);
			UserMap.UserId2TokenMap.put(pd.getString("userId"), tui);
			wxLRep.setOpenId(null);
			wxLRep.setToken(token);
			wxLRep.setUserId(pd.getString("userId"));
			
			WxUserRep wxURep = new WxUserRep();
			wxURep.setAvatarUrl(pd.getString("avatarUrl"));
			wxURep.setCity(pd.getString("city"));
			wxURep.setCountry(pd.getString("country"));
			wxURep.setGender(pd.getString("gender"));
			wxURep.setLanguage(pd.getString("language"));
			wxURep.setNickName(Base64CC.encode(pd.getString("nickName")));
			wxURep.setProvince(pd.getString("province"));
			wxURep.setUserName(Base64CC.encode(pd.getString("userName")));
			wxURep.setUnionId(wxLogin.getUnionid());
			wxURep.setSession_key(wxLogin.getSession_key());
			
			wxLRep.setUser(wxURep);
		}
		
		return wxLRep;
	}
	
}
